package com.gxc.blogm.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.servlet.ModelAndView;

import com.gxc.authcore.system.util.CurrentUtil;
import com.gxc.authcore.system.util.ParamUtil;
import com.gxc.blogm.domain.Media;
import com.gxc.blogm.service.MediaService;
import com.gxc.webcore.util.FileUtil;
import com.gxc.webcore.util.JsonUtil;
import com.gxc.webcore.util.StringUtil;

public class KindeditorController {

	MediaService mediaService;

	public MediaService getMediaService() {
		return mediaService;
	}

	public void setMediaService(MediaService mediaService) {
		this.mediaService = mediaService;
	}

	/**
	 * kindeditor 上传文件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView uploadFile(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		Map map = new HashMap();
		String fileName = "";
		String fileUrl = "";
		String filePath = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			for (Object item1 : items) {
				FileItem item = (FileItem) item1;
				if (!item.isFormField()) {
					// 获取上传本地文件的名字不包括其路径
					fileName = item.getName();
					fileName = fileName.substring(fileName
							.lastIndexOf(File.separator) + 1);
					String suffix = "";
					if (fileName.lastIndexOf(".") > 0) {
						suffix = fileName.substring(fileName.lastIndexOf("."));
					}
					String newName = StringUtil.getUUID() + suffix;
					String folderPath = request.getSession()
							.getServletContext().getRealPath("/resources/myblog");
					filePath = folderPath + "/" + newName;
					File uploadFile = new File(filePath);
					// 将文件保存到服务器
					item.write(uploadFile);
					fileUrl = ParamUtil.get("url_local") + "/resources/myblog"
							+ newName;
					map.put("error", 0);
				}
			}
		} catch (Exception e) {
			map.put("error", 1);
		}
		map.put("url", fileUrl);
		String jsonpResult = JsonUtil.object2json(map);

		// 写入数据库
		Media picture = new Media();
		picture.setId("picture_" + StringUtil.getUUID());
		picture.setFile_name(fileName);
		picture.setUrl(fileUrl);
		picture.setPath(filePath);
		picture.setFile_type(1);
		picture.setCreate_user(CurrentUtil.getAuthUser().getId());
		picture.setCreate_time(new Date());
		picture.setUpdate_time(new Date());
		mediaService.create(picture);

		response.getWriter().write(jsonpResult);
		return null;
	}

	/**
	 * kindeditor 浏览文件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ModelAndView listFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map map = new HashMap();
		map.put("current_dir_path", "");
		map.put("current_url", ParamUtil.get("url_local") + "/resources/myblog/");
		map.put("moveup_dir_path", "");

		List file_list = new ArrayList();
		String dirPath = request.getSession().getServletContext()
				.getRealPath("/resources/myblog");
		File dir = new File(dirPath);
		File[] files = dir.listFiles();
		List<File> list = FileUtil.sortDown(files);
		// 设置最多返回20个文件信息
		int i = 20;
		for (File file : list) {
			Map item = new HashMap();
			if (file.isDirectory()) {
				continue;
			}
			if (i > 0) {
				String filename = file.getName();
				String suffix = filename.substring(
						filename.lastIndexOf(".") + 1, filename.length());
				item.put("datetime", new Date(file.lastModified()));
				item.put("dir_path", "");
				item.put("filename", file.getName());
				item.put("filesize", file.length());
				item.put("filetype", suffix);
				item.put("has_file", false);
				item.put("is_dir", false);
				item.put("is_photo", true);
				file_list.add(item);
			}
			i--;
		}
		map.put("file_list", file_list);
		String jsonResult = JsonUtil.object2json(map);
		response.getWriter().write(jsonResult);
		return null;
	}
}
